package com.cas;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import com.cas.scalls.util.SqliteUtil;

public class test {
	static Connection conn = null;
	static Statement stat = null;
	static boolean inuse = false;



	public static void main(String[] args) {
		try {
			thread1 th1 = new thread1();
			th1.start();
			thread2 th2 = new thread2();
			th2.start();
		}catch(Exception e){
			
		}
	}

	public static ResultSet select(String sql) throws Exception {
		while (getToken() == false)
			Thread.sleep(50);
		ResultSet rs = stat.executeQuery(sql);
		releaseToken();
		return rs;
	}

	public static int insertOrUpdate(String sql) throws Exception {
		while (getToken() == false)
			Thread.sleep(50);
		int ret = stat.executeUpdate(sql);
		releaseToken();
		return ret;
	}

	synchronized public static boolean getToken() {
		if (inuse)
			return false;
		else {
			inuse = true;
			return true;
		}

	}

	synchronized public static void releaseToken() {
		inuse = false;
	}

}

class thread1 extends Thread {

	public void run() {
		try {
			// 连接SQLite的JDBC
			int i = 0;
			while (true) {
				i++;
				if (i % 10 == 0)
					Thread.sleep(1000);
				// 建立一个数据库名zieckey.db的连接，如果不存在就在当前目录下创建之

				ResultSet rs = SqliteUtil
						.select("select * from tbl9 order by name desc limit 1 offset 1;");

				while (rs.next()) { // 将查询到的数据打印出来

					System.out.print("name = " + rs.getString("name") + " "); // 列属性一

					System.out.println("salary = " + rs.getString("salary")); // 列属性二

				}
				rs.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

class thread2 extends Thread {

	public void run() {
		try {
			// 连接SQLite的JDBC
			int i = 0;
			while (true) {
				i++;
				if (i % 10 == 0)
					Thread.sleep(1000);
				// 建立一个数据库名zieckey.db的连接，如果不存在就在当前目录下创建之
				int ret = SqliteUtil.insertOrUpdate("insert into tbl9 values('"
						+ System.currentTimeMillis() + "',7800);");
				System.out.println(ret);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
